package lua.compiler.tokens;
import lua.compiler.CompilerException;
import lua.compiler.Function;

import org.antlr.runtime.tree.Tree;


public class IfToken extends GenericToken {

	@Override
	public void parseImpl(Tree tree, Function function) throws CompilerException {
		// ewaluujemy expression, na stosie zostaje 0 albo 1
		new ExpToken().parse(tree.getChild(0), function); //warunek if-a
		
		boolean elseOccured = false;

		String afterLabel = "_CONTINUE" + tree.getLine();
		String elseLabel = "_ELSE" + tree.getLine();
		
		// jesli nie jest spelniony, przeskakujemy za cialo if-a, ale przed else-a (brfalse)
		function.addInstruction("brfalse " + elseLabel);
		
		for (int i = 1; i < tree.getChildCount(); i++) {
			String token = Tokens.getToken(tree.getChild(i).getType());
			
			if (token.startsWith("ELSE")) {
				elseOccured = true;
				// jesli warunek if-a byl spelniony, to else nie moze sie wykonac
				// wiec skaczemy za else-a
				function.addInstruction("br " + afterLabel);
				function.addInstruction(elseLabel + ":");
				new StmtToken().parse(tree.getChild(i).getChild(0), function);
			}
			else {
				new StmtToken().parse(tree.getChild(i), function);
			}
		}
		
		if (!elseOccured) // nie wystapil else, skok z poczatku musi tu wyladowac
			function.addInstruction(elseLabel + ":");
		function.addInstruction(afterLabel + ":");
	}
}